#include "path.h"
#include "ams_path.h"
#include "coap_ext.h"
#include "cJSON_ext.h"
#include "misc.h"
#include "coap_sdk.h"

void wa_config_set_target(const char* target_type, const char* target_id)
{
    char path[PATH_LEN];
    snprintf(path, sizeof(path), "%stargets.cfg", get_config_path());
    cJSON * j_root = load_json_file_A(path);
    if(j_root == NULL)
        j_root = cJSON_CreateObject();

    cJSON * j_targets = cJSON_GetObjectItem(j_root, "targets");
    if(j_targets == NULL)
    {
        j_targets = cJSON_AddArrayToObject(j_root, "targets");
    }
    cJSON * j_item;
    cJSON_ArrayForEach(j_item, j_targets)
    {
        cJSON * j_tt = cJSON_GetObjectItem(j_item, "tt");
        cJSON * j_ti = cJSON_GetObjectItem(j_item, "tid");
        if(strcmp(j_tt->valuestring, target_type) == 0 &&
            strcmp(j_ti->valuestring, target_id) == 0)
        {
            break;
        }
    }

    // add new entry
    if(j_item == NULL)
    {
        char query[128];
        cJSON * j_item = cJSON_CreateObject();
        cJSON_AddStringToObject(j_item, "tt", target_type);
        cJSON_AddStringToObject(j_item, "tid", target_id);
        cJSON_AddItemToArray(j_targets, j_item);

        save_json_file(j_root, path);

        if(get_product_name())
        {
            coap_packet_t coap_message [1];
            coap_init_message(coap_message, COAP_TYPE_NON, COAP_PUT, coap_get_mid());
            snprintf(query, sizeof(query), "update=%s", get_product_name());
            coap_set_header_uri_path(coap_message, "ams/config_checkpoint");
            coap_set_header_uri_query(coap_message, query);
            wa_coap_send_packet_IP(coap_message, "127.0.0.1", 2233);
        }
    }
    cJSON_Delete(j_root);
}



char* wa_query_ams_verion(coap_context_t * coap_ctx, char* buffer, int len)
{

    char* ret = NULL;
    coap_packet_t request[1];
    memset(request, 0, sizeof(coap_packet_t));
    coap_init_message(request, COAP_TYPE_CON, COAP_GET, coap_get_mid());
    coap_set_header_uri_path(request, "ams/version");

    uip_ipaddr_t addr;
    set_addr_ip(&addr, "127.0.0.1", 2233);
    coap_request_user_data_t * data = make_blocking_request(coap_ctx,
            request, &addr);

    if(data && data->result == Success)
    {
        ret = buffer;
    }

    if(data) free_coap_request_user_data(data);
    return ret;
}
